package com.awei.study.design.structure.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author liweilong
 * @Date 2024/8/3 10:17
 * 动态代理——CGLib代理
 */
public class CGLibProxy {

    public abstract class test {
        public abstract void sell2();
    }

    public static class TrainSell {
        public void sell() {
            System.out.println("火车站卖票");
        }
        public void sell1() {
            System.out.println("火车站卖票1");
        }
    }


    public static class ProxyFactory implements MethodInterceptor {
        private TrainSell trainSell = new TrainSell();

        public TrainSell getProxyObject () {
            Enhancer enhancer = new Enhancer();
            //设置父类的字节码对象
            enhancer.setSuperclass(trainSell.getClass());
            //设置回调函数
            enhancer.setCallback(this);
            //创建代理对象
            TrainSell trainSell = (TrainSell) enhancer.create();
            return trainSell;
        }

        @Override
        public TrainSell intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("收取中介费");
            TrainSell o1 = (TrainSell) methodProxy.invokeSuper(o, objects);
            return o1;
        }

//        @Override
//        public void sell2() {
//            System.out.println();
//        }
    }

    public static void main(String[] args) {
        ProxyFactory proxyFactory = new ProxyFactory();
        TrainSell proxyObject = proxyFactory.getProxyObject();
        proxyObject.sell();
        proxyObject.sell1();
    }
}
